package com.dinadi.yidi.service;

import android.Manifest;
import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.dinadi.yidi.http.ServiceUtil;
import com.dinadi.yidi.utils.CommonUtil;

import java.io.File;

/**
 * 作者：machao on 2016/4/12 17:56
 * APK 升级
 * Created by Administrator on 2016/4/12.
 */
public class UpDataVersionService extends IntentService {
    // 定义下载目录： /mnt/sdcard/com.itheima.googleplay78/download
    public static String DOWNLOAD_DIR = Environment.getExternalStorageDirectory()
            + File.separator
            + CommonUtil.getContext().getPackageName()
            + File.separator
            + "download";

    public UpDataVersionService() {
        super("UpDataVersionService");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String downAPKUrl = intent.getStringExtra("downAPKUrl");
        ServiceUtil.requestDownAPK(downAPKUrl, DOWNLOAD_DIR, "yidi.apk", new ServiceUtil.RequestCallBack<File>() {
            @Override
            public void onSuccess(File result) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setDataAndType(Uri.fromFile(result),
                        "application/vnd.android.package-archive");
                CommonUtil.getContext().startActivity(i);
                stopSelf();
            }

            @Override
            public void onFailure(String error) {
                Log.i("faile", "shibai");
                stopSelf();
            }


        }, null);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }
}
